'''
DocIndexer abstract parser.
'''
import sys, os
from common import EDocIndexer, mime_type, Conf, decode_input, safe_print

class AbstractParser(object):

    description = ''
    mime_types = []

    def __init__(self):
        '''Check all parser resouces are available, throw EDocIndexer error if
        not.'''
        pass

    def close(self):
        '''Cleanup.'''
        pass

    def text(self,filename):
        '''Return file contents as text string.'''
        raise NotImplementedError

    def additional_fields(self):
        '''Return list of parser specific additional Lucene fields.
        Called after self.text().'''
        return []

    @classmethod
    def unicode(cls,text):
        __pychecker__ = 'unusednames=cls'
        return decode_input(text,'replace')

    @classmethod
    def handles(cls,mimetype):
        '''Return True if parser class handles MIME type.'''
        return mimetype in cls.mime_types

    @classmethod
    def isused(cls):
        '''Returns True if parser MIME types have at least one entry in the
        docindexer.conf file.'''
        for mime in cls.mime_types:
            if mime in Conf.mime_dict.values():
                return True
        return False

    @classmethod
    def test(cls):
        if len(sys.argv) != 2:
            safe_print('usage: %s filename' % os.path.basename(sys.argv[0]))
            sys.exit(1)
        filename = sys.argv[1]
        try:
            parser = cls()
        except EDocIndexer, e:
            print 'failed:',e
            sys.exit(1)
        if not parser.handles(mime_type(filename)):
            print 'failed: parser cannot handle file'
        else:
            try:
                safe_print(parser.text(filename))
            except EDocIndexer, e:
                print 'failed:',e
                sys.exit(1)
            finally:
                parser.close()
            sys.exit(0)

# vim: ts=4 sw=4:
